/**
 * 2. 两数相加
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
const { ListNode, displayListNode, createListNode } = require('../../libs/public');

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
const addTwoNumbers = (l1, l2) => {
  let result = null;
  let l1Cur = l1;
  let l2Cur = l2;
  let resultCur;
  let carry = 0;
  while (l1Cur || l2Cur) {
    const sum = (l1Cur ? l1Cur.val : 0) + (l2Cur ? l2Cur.val : 0) + carry;
    let val = sum;
    if (sum > 9) {
      carry = 1;
      val = sum % 10;
    } else {
      carry = 0;
    }
    if (!result) {
      result = new ListNode(val);
      resultCur = result;
    } else {
      resultCur.next = new ListNode(val);
      resultCur = resultCur.next;
    }
    if (l1Cur) l1Cur = l1Cur.next;
    if (l2Cur) l2Cur = l2Cur.next;
  }
  if (carry) {
    resultCur.next = new ListNode(1);
  }
  return result;
};

console.log(displayListNode(addTwoNumbers(createListNode([0]), createListNode([1]))) === '[1]');
